const express = require('express');
const router = express.Router();
const { query } = require('../config/database');

// 获取热销商品（相关商品推荐）
router.get('/hot', async (req, res) => {
  console.log('=== /goods/hot 接口被调用 ===');
  console.log('请求参数:', req.query);
  
  try {
    const { id, type, limit = 3 } = req.query;
    const parsedLimit = parseInt(limit) || 3;
    const parsedId = parseInt(id) || 0;
    
    // 先测试数据库连接和表结构
    const testQuery = 'SHOW TABLES LIKE "sys_goods"';
    const tableExists = await query(testQuery);
    console.log('sys_goods表是否存在:', tableExists);
    
    if (tableExists.length === 0) {
      // 如果sys_goods表不存在，返回模拟数据
      const mockData = [
        {
          id: 1,
          name: '热销商品1',
          desc: '这是一个热销商品',
          price: '99.00',
          picture: 'https://example.com/pic1.jpg',
          orderNum: 100
        },
        {
          id: 2,
          name: '热销商品2',
          desc: '这是另一个热销商品',
          price: '199.00',
          picture: 'https://example.com/pic2.jpg',
          orderNum: 90
        },
        {
          id: 3,
          name: '热销商品3',
          desc: '第三个热销商品',
          price: '299.00',
          picture: 'https://example.com/pic3.jpg',
          orderNum: 80
        }
      ];
      
      res.json({
        code: '1',
        msg: '操作成功（模拟数据）',
        result: mockData.slice(0, parseInt(limit))
      });
      return;
    }
    
    let hotGoodsQuery;
    let queryParams = [];
    
    if (type === '1') {
      // 24小时热销榜
      hotGoodsQuery = `
        SELECT 
          g.goods_id as id,
          g.goods_name as name,
          g.goods_desc as \`desc\`,
          g.goods_price as price,
          g.goods_picture as picture,
          g.goods_orderNum as orderNum
        FROM sys_goods g
        WHERE g.goods_id != ?
        ORDER BY g.goods_orderNum DESC
        LIMIT ?
      `;
      queryParams = [parsedId, parsedLimit];
    } else if (type === '2') {
      // 周热销榜
      hotGoodsQuery = `
        SELECT 
          g.goods_id as id,
          g.goods_name as name,
          g.goods_desc as \`desc\`,
          g.goods_price as price,
          g.goods_picture as picture,
          g.goods_orderNum as orderNum
        FROM sys_goods g
        WHERE g.goods_id != ?
        ORDER BY g.goods_orderNum DESC
        LIMIT ?
      `;
      queryParams = [id || 0, parseInt(limit)];
    } else if (type === '3') {
      // 总热销榜
      hotGoodsQuery = `
        SELECT 
          g.goods_id as id,
          g.goods_name as name,
          g.goods_desc as \`desc\`,
          g.goods_price as price,
          g.goods_picture as picture,
          g.goods_orderNum as orderNum
        FROM sys_goods g
        WHERE g.goods_id != ?
        ORDER BY g.goods_orderNum DESC
        LIMIT ?
      `;
      queryParams = [parsedId, parsedLimit];
    } else {
      // 默认获取热销商品（按销量排序）
      hotGoodsQuery = `
        SELECT 
          g.goods_id as id,
          g.goods_name as name,
          g.goods_desc as \`desc\`,
          g.goods_price as price,
          g.goods_picture as picture,
          g.goods_orderNum as orderNum
        FROM sys_goods g
        ORDER BY g.goods_orderNum DESC
        LIMIT ${parsedLimit}
      `;
      queryParams = [];
    }
    
    const hotGoods = await query(hotGoodsQuery, queryParams);
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: hotGoods
    });
  } catch (error) {
    console.error('获取热销商品失败:', error);
    res.json({
      code: '0',
      msg: '获取热销商品失败',
      result: null
    });
  }
});

// 获取相关商品推荐（别名接口）
// 获取相关商品推荐
router.get('/relevant', async (req, res) => {
  console.log('=== /goods/relevant 接口被调用 ===');
  console.log('请求参数:', req.query);
  
  try {
    const { id, limit = 16 } = req.query;
    const parsedLimit = parseInt(limit) || 16;
    const parsedId = parseInt(id) || 0;
    
    // 查询相关商品（排除当前商品，按销量排序）
    const relevantGoodsQuery = `
      SELECT 
        g.goods_id as id,
        g.goods_name as name,
        g.goods_desc as \`desc\`,
        g.goods_price as price,
        g.goods_picture as picture,
        g.goods_orderNum as orderNum
      FROM sys_goods g
      WHERE g.goods_id != ${parsedId}
      ORDER BY g.goods_orderNum DESC
      LIMIT ${parsedLimit}
    `;
    
    const relevantGoods = await query(relevantGoodsQuery, []);
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: relevantGoods
    });
  } catch (error) {
    console.error('获取相关商品失败:', error);
    res.json({
      code: '0',
      msg: '获取相关商品失败',
      result: null
    });
  }
});

module.exports = router;